package com.tianya.forum.service.impl;

import com.tianya.forum.common.AppResult;
import com.tianya.forum.common.ResultCode;
import com.tianya.forum.dao.ArticleReplyMapper;
import com.tianya.forum.exception.ApplicationException;
import com.tianya.forum.model.ArticleReply;
import com.tianya.forum.service.IArticleReplyService;
import com.tianya.forum.service.IArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private IArticleService articleService;



    @Override
    public void creat(ArticleReply articleReply) {
        if(articleReply == null || articleReply.getArticleId() == null || articleReply.getContent() == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 填充默认数据
        articleReply.setState((byte) 0); // 状态
        articleReply.setDeleteState((byte) 0); // 是否状态
        articleReply.setLikeCount(0); // 点赞数量
        // 时间
        Date date = new Date();
        articleReply.setCreateTime(date); // 创建时间
        articleReply.setUpdateTime(date); // 更新时间

        //写入回复表
        int row = articleReplyMapper.insert(articleReply);
        if(row != 1){
            // 记录⽇志
            log.info("新增帖⼦回复失败, userId = " +
                    articleReply.getPostUserId() + ", articleId = " + articleReply.getArticleId());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //修改帖子表回复数
        articleService.addOneReplyCount(articleReply.getArticleId());
        // ⽇志
        log.info("新增帖⼦回复成功, userId = " + articleReply.getPostUserId() +
                ", articleId = " + articleReply.getArticleId() + ", articleReplyId = " + articleReply.getId());

    }


    /**
     * 查询帖⼦对应的回复
     * @param articleId 帖⼦Id
     * @return 帖子回复
     */
    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if(articleId == null || articleId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO层查询结果
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        //返回结果
        return articleReplies;
    }
}